import Vue from 'vue'
import Vuex from 'vuex'
import { Notification } from 'element-ui';

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
	state: {
		currentSessionId: "-1",// 对方频道号，想要发送消息对别人，就要知道对方的频道
		filterKey: '',
		user: {}, //当前用户
		websock: null,// WebSocket对象	
		eventlist: [],	//onmessage 返回的数据
		baseUrl: "http://localhost:8282/",
		sessions: [],//所有会话，含用户信息及聊天记录
	},
	getters: {
		eventlist(state) {
			return state.eventlist;
		},
		websock(state) {
			return state.websock;
		},
		getMyUser(state) {
			return state.user;
		},
		getMySessions(state) {
			return state.sessions;
		},
	},
	mutations: {
		initWebSock(state, url) {

			state.websock = new WebSocket(url);
			state.websock.onopen = function () {
				console.log("连接成功！");
			};

			state.websock.οnerrοr = function (e) { //错误
				console.log("ws错误!");
				console.log(e);
			};

			state.websock.onclose = function () { //关闭
				console.log("监听连接关闭!");
			};

			let that = this;

			state.websock.onmessage = function (e) {
				let msgObj = eval("(" + e.data + ")");
				console.info(msgObj);
				if (msgObj.type === 0) {//有用户建立连接
					if (state.user.aisle == undefined) {//用户首次登录
						const num = Math.ceil((Math.random() * 1000000000) % 9);
						let tempUser = {};
						tempUser.name = msgObj.name;
						tempUser.img = num;
						tempUser.avatar = state.baseUrl + "images/" + num + ".jpeg";
						tempUser.aisle = msgObj.aisle;
						state.user = tempUser;//用户本人						
					}

					const oldSS = state.sessions;
					let newSS = [];
					for (var key in msgObj.people) {
						let iffind = false;
						oldSS.forEach(os => {
							if (key == os.id) {
								newSS.push(os);
								iffind = true;
							}
						});
						if (!iffind) {
							//新的							
							const num = Math.ceil((Math.random() * 1000000000) % 9);
							let obj = {};
							obj.id = key;
							obj.userName = msgObj.people[key];
							obj.aisle = key;
							obj.avatar = state.baseUrl + "images/" + num + ".jpeg";
							obj.hasNew = false;
							obj.messages = [];
							if (key != state.user.aisle) {
								newSS.push(obj);
							}
						}
					}
					state.sessions = newSS;


				} else if (msgObj.type === 1) {//接收到服务器（用户）发来的消息
					that.commit('addMessage', msgObj);
				} else if (msgObj.type === 2) {//有用户退出

					const oldSS = state.sessions;
					let newSS = [];
					for (var key in msgObj.people) {
						let iffind = false;
						oldSS.forEach(os => {
							if (key == os.id) {
								newSS.push(os);
								iffind = true;
							}
						});
						if (!iffind) {
							//新的							
							const num = Math.ceil((Math.random() * 1000000000) % 9);
							let obj = {};
							obj.id = key;
							obj.userName = msgObj.people[key];
							obj.aisle = key;
							obj.avatar = state.baseUrl + "images/" + num + ".jpeg";
							obj.hasNew = false;
							obj.messages = [];
							if (key != state.user.aisle) {
								newSS.push(obj);
							}
						}
					}
					state.sessions = newSS;
				}

			}
		},
		//将接收到的数据赋值
		WebSockOnMessage(state, data) {
			state.eventlist = data;
		},
		changeCurrentSessionId(state, id) {
			state.currentSessionId = id;
			//点击聊天对象后，取消新消息提示
			state.sessions.forEach(element => {
				if (element.id == id) {
					element.hasNew = false;//新消息提示
				}
			});
		},
		addMessage(state, Obj) {

			for (let index = 0; index < state.sessions.length; index++) {
				const el = state.sessions[index];

				if (el.id == Obj.toid) {
					//发信人
					el.messages.push({
						content: Obj.msg,
						date: new Date(),
						self: true//state.user.aisle == Obj.toid ? true : false
					})
				}
				else if (el.id == Obj.fromid) {
					//收信人
					el.messages.push({
						content: Obj.msg,
						date: new Date(),
						self: false///state.user.aisle == Obj.fromid ? true : false
					})
				}


				if (Obj.toid == state.user.aisle && Obj.fromid != state.currentSessionId) {			
					//找出发来的人的名称
					state.sessions.forEach(element => {
						if (element.id == Obj.fromid) {
							Notification.success({
								title: "提示",
								message: '【' + element.userName + "】发来的了消息",
								type: "success",
								position: 'bottom-right'
							});
							element.hasNew = true;//新消息提示
						}
					});
				}
			}
		},
		sendMsg(state, data) {
			state.websock.send(data);
		},
		INIT_DATA(state, data) {
			state.sessions = [];
			if (data) {
				//state.sessions = JSON.parse(data);
				state.sessions = data;
			}
		},
		setUser(state, user) {
			state.user = user;
		},
		setmyAisle(state, myAisle) {
			state.myAisle = myAisle;
		},
		setSessions(state, ss) {
			state.sessions = ss;
		},

	},
	actions: {
		initData(context) {
			context.commit('INIT_DATA')
		},
		WEBSOCKET_INIT({ commit }, url) {
			commit('initWebSock', url);
		},
		//发送消息
		WEBSOCKET_SEND({ commit }, data) {
			//let _msg = JSON.stringify(data);	
			commit('sendMsg', data);
		}
	}
})


store.watch(function (state) {
	return state.sessions
}, function (val) {
	console.log('CHANGE: ', val);
	localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
	deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;